/*
 * NoticiaAutomatica.java
 *
 * Created on 11 / desembre / 2008, 08:31
 */

package Vistas;
import java.io.File;
import javax.swing.JFileChooser;
import java.awt.event.*;
import java.util.Vector;
import Dominio.CtrlDominio;
import Dominio.NoticiaNoValidaException;
import Dominio.Strouble;
import Dominio.VecTitTex;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author  pedro
 */
public class NoticiaAutomatica extends javax.swing.JFrame {
    private int idioma;
    private int nsel;
    CtrlDominio CD=CtrlDominio.getInstance();
    private static String[] Temas = {"Temas"};
    private static String[] Noticias = {"Noticias"};
    private Vector<AuxNoticia> manual=new Vector<AuxNoticia>(0,1);
    private Vector<AuxNoticia> auto= new Vector<AuxNoticia>(0,1);
    /** Creates new form NoticiaAutomatica */
    public NoticiaAutomatica(int id) {
        idioma=id;
        nsel=-1;
        initComponents();
        jComboBox1.addItem("");
        jComboBox1.addItem("Nacional");jComboBox1.addItem("Internacional");jComboBox1.addItem("Economia");
        jComboBox1.addItem("Ciencia");jComboBox1.addItem("Espectaculos");jComboBox1.addItem("Salud");jComboBox1.addItem("Deportes");
        jComboBox1.addItem("Gente");jComboBox1.addItem("Auto");
        this.setTitle("Clasificar autom\u00e1ticamente");
        this.setLocationRelativeTo(null);
        jButton3.setEnabled(false);
        String fs = System.getProperty("file.separator");
        ImageIcon ic = new ImageIcon(System.getProperty("user.dir") + fs + "src" + fs + "Image" + fs + "open.png");
        jButton1.setIcon(ic);
        ImageIcon ic2 = new ImageIcon(System.getProperty("user.dir") + fs + "src" + fs + "Image" + fs + "return.png");
        jButton2.setIcon(ic2);
        ImageIcon ic3 = new ImageIcon(System.getProperty("user.dir") + fs + "src" + fs + "Image" + fs + "save.png");
        jButton3.setIcon(ic3);
        
    }
    
    private void clasifauto(String path){
    manual=new Vector<AuxNoticia>(0,1);
    auto= new Vector<AuxNoticia>(0,1);
    File a=new File(path);    
    Vector<Strouble> st=new Vector<Strouble>(0,1);
    File[] cjtar;
    Vector<String> phat=new Vector<String>(0,1);
    Vector<VecTitTex> vtt=new Vector<VecTitTex>(0,1);
    //JFileChooser fc=new JFileChooser(path);
    //fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    //BasicDirectoryModel dir=new BasicDirectoryModel(fc);
    cjtar=a.listFiles(new Dominio.NoticiaFilter());
    System.out.println(cjtar.length);
    try{
    for(int i=0;i<cjtar.length;i++){
        String pth=cjtar[i].getAbsolutePath();
        System.out.println(i+" "+pth);
        vtt.addElement(CD.clasificar(pth));
        //System.out.println(i);
        phat.addElement(pth);
    }
    String secc=(String)jComboBox1.getSelectedItem();
    Vector<Boolean> rep=new Vector<Boolean>(0,1);
    rep=estanRepetidos(vtt);
    for(int i=0;i<vtt.size();i++){
        if(!rep.get(i)){
            st=new Vector<Strouble>(0,1);            
            st=CD.sacaTemas(vtt.get(i),secc);
            AuxNoticia N=new AuxNoticia();
            N.titulo=vtt.get(i).tit;
            N.path=phat.get(i);
            N.palabras=vtt.get(i).vec;
            N.temas=new Vector<String>(0,1);
            N.seccion=secc;
            if(st.isEmpty())            
                manual.addElement(N);
            else{
                if(st.get(0).dist==0){
                    manual.addElement(N);
                }
                else{             
                    N.temas.addElement(st.get(0).nom);
                    for(int j=1;j<st.size() && N.temas.size()<3;j++){
                        if(st.get(j).dist>=0.2)
                            N.temas.addElement(st.get(j).nom);
                    }
                    auto.addElement(N);
                }
            }
        }       
    }
    jButton3.setEnabled(true);
    jComboBox1.setEnabled(false);
    int dimension=manual.size()+auto.size();
    String[][] tabla=new String[dimension][1];
    for(int i=0;i<auto.size();i++)
        tabla[i][0]=auto.get(i).titulo;
    for(int i=0;i<manual.size();i++)
        tabla[i+auto.size()][0]=manual.get(i).titulo;
    jTable1.setModel(new javax.swing.table.DefaultTableModel(tabla, Noticias));
    nsel=0;
    /*if(auto.size()>0){
        tabla=new String[auto.get(0).temas.size()][1];
        for(int i=0;i<auto.get(0).temas.size();i++){
            tabla[i][0]=auto.get(0).temas.get(i);
        }
    }
    else if(manual.size()>0){
        tabla=new String[1][1];
        tabla[0][0]="temas incompatibles";
    }
    else{
       tabla=new String[0][1];
    }
     jTable2.setModel(new javax.swing.table.DefaultTableModel(tabla, Temas));*/
    actualizarTabla();
     }
    
    catch(NoticiaNoValidaException e){
        JOptionPane.showMessageDialog(null, "Noticia no v\u00e1lida");
    }
    catch (MalformedURLException e) {
            JOptionPane.showMessageDialog(null, "URL no v\u00e1lida");
            }
    catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Error de lectura/escritura");
        }
     catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: "+e);
        }
    
}
    
private Vector<Boolean> estanRepetidos(Vector<VecTitTex>vx){
        Vector<Boolean> b=new Vector<Boolean>();
        Vector<String> aux=new Vector<String>();
        for(VecTitTex p:vx){
            if(!aux.contains(p.tit)){
                if(!CD.estaDiccionarioNoticias(p.tit))
                    b.add(false);
                else b.add(true);
            }
            else{
                b.add(true);
                int i=aux.indexOf(p.tit);
                b.set(i,true);
            }
            aux.add(p.tit);
        }
        return b;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("introduce un directorio");
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        jButton1.setText("Abrir Directorio");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null}
            },
            new String [] {
                "Temas"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setResizable(false);

        jButton3.setText("Guardar");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton2.setText("Volver");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Noticia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jTable1MouseEntered(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(45, 45, 45)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31))
        );

        jLabel1.setText("Seccion");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(41, 41, 41)
                        .addComponent(jButton1)))
                .addContainerGap(106, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
    if(evt.KEY_TYPED==evt.VK_ENTER){
        clasifauto(jTextField1.getText());
    }
}//GEN-LAST:event_jTextField1KeyTyped

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
    if(((String)jComboBox1.getSelectedItem()).equals(""))
        JOptionPane.showMessageDialog(null, "Introduce la Seccion por favor");
    else{
    JFileChooser tdir= new JFileChooser();
    tdir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int seleccion = tdir.showOpenDialog(jButton1);
        if (seleccion == JFileChooser.APPROVE_OPTION) {
            File Directorio = tdir.getSelectedFile();
            jTextField1.setText(Directorio.getAbsolutePath());
            //System.out.println(Directorio.isDirectory());
            clasifauto(jTextField1.getText());
        }
    }
}//GEN-LAST:event_jButton1MouseClicked

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
    this.dispose();
    new menu(idioma).setVisible(true);
}//GEN-LAST:event_jButton2MouseClicked

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
    nsel=jTable1.getSelectedRow();
    if(nsel>-1)
        actualizarTabla();    
}//GEN-LAST:event_jTable1MouseClicked

private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
   CD.guardarClasificacionAutomatica(auto, manual);
   this.dispose();
   new menu(idioma).setVisible(true);
}//GEN-LAST:event_jButton3MouseClicked

private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
    if(jTable2.getValueAt(0,0)=="temas incompatibles"){
        new AddAutoTema(manual.get(nsel-auto.size()),this,(String)jComboBox1.getSelectedItem()).setVisible(true);
        desactivar();
    }
}//GEN-LAST:event_jTable2MouseClicked

private void jTable1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseEntered
    if (jTable1.getSelectedRow() != -1) {
    jTable1.setToolTipText((String) (jTable1.getValueAt(jTable1.getSelectedRow(), 0)));     // TODO add your handling code here:
    }
}//GEN-LAST:event_jTable1MouseEntered

private void desactivar(){
    jButton1.setEnabled(false);
    jButton2.setEnabled(false);
    jButton3.setEnabled(false);
}

public void activar(){
    jButton1.setEnabled(true);
    jButton2.setEnabled(true);
    jButton3.setEnabled(true);
}

public void actualizarTabla(){
    int dimension=auto.size()+manual.size();
    if(dimension>0){
    String tabla[][];
    int focus=nsel;
    //System.out.println(focus);
    if(focus<auto.size()){
        //System.out.print("auto");
        tabla=new String[auto.get(focus).temas.size()][1];
        for(int i=0;i<auto.get(focus).temas.size();i++){
            tabla[i][0]=auto.get(focus).temas.get(i);
        }
    }
    else{
        focus=nsel-auto.size();
        //System.out.print("manual "+focus);
        tabla=new String[manual.get(focus).temas.size()+1][1];
        if (manual.get(focus).temas.size()>0){
            for(int i=0;i<manual.get(focus).temas.size();i++){
                tabla[i][0]=manual.get(focus).temas.get(i);
            }
            tabla[manual.get(focus).temas.size()][0]="**Temas agregados**";
        }
        else
        tabla[0][0]="temas incompatibles";
    }    
     jTable2.setModel(new javax.swing.table.DefaultTableModel(tabla, Temas));
    }
}
    /**
    * @param args the command line arguments
    */
    /*public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() 
                new NoticiaAutomatica().setVisible(true);
            }
        });
    }*/

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}
